package com.robcity.platform.util;

public class WGS84ToGCJ02 {

    // Constants for GCJ-02 transformation
    private static final double PI = 3.1415926535897932384626;
    private static final double A = 6378245.0;
    private static final double EE = 0.00669342162296594323;

    // Method to convert WGS-84 to GCJ-02
    public static double[] wgs84ToGcj02(double lat, double lon) {
        if (outOfChina(lat, lon)) {
            return new double[]{lat, lon};
        }
        double dLat = transformLat(lon - 105.0, lat - 35.0);
        double dLon = transformLon(lon - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * PI;
        double magic = Math.sin(radLat);
        magic = 1 - EE * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI);
        dLon = (dLon * 180.0) / (A / sqrtMagic * Math.cos(radLat) * PI);
        double mgLat = lat + dLat;
        double mgLon = lon + dLon;
        return new double[]{ mgLon, mgLat};
    }

    private static boolean outOfChina(double lat, double lon) {
        return !(lon > 73.66 && lon < 135.05 && lat > 3.86 && lat < 53.55);
    }

    private static double transformLat(double x, double y) {
        double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    private static double transformLon(double x, double y) {
        double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
        return ret;
    }

    public static void main(String[] args) {
            double[] wgs84 = {22.6953355,114.213295};
            double[] gcj02 = wgs84ToGcj02(wgs84[0],wgs84[1]);
            System.out.printf("WGS84经度：%s\n",wgs84[1]);
            System.out.printf("WGS84纬度：%s\n",wgs84[0]);
            System.out.printf("GCJ02经度：%s\n",gcj02[0]);
            System.out.printf("GCJ02纬度：%s\n",gcj02[1]);

            /*
                WGS84经度：114.213469166666
                WGS84纬度：22.695753
                GCJ02经度：114.21835072124392
                GCJ02纬度：22.69293659604072 

                WGS84经度：114.213295
                WGS84纬度：22.6953355
                GCJ02经度：114.21817687866768
                GCJ02纬度：22.692519210517034
            */
            // Add more coordinates here
    }
}